#include "collaborationwidget.h"
#include <QSqlError>
#include <QMessageBox>
#include <QDebug>
#include <QHeaderView>
#include <QLabel>
#include <QDialog>
#include <QFormLayout>
#include <QLineEdit>
#include <QComboBox>
#include <QDialogButtonBox>
#include <QSqlQuery>
#include <QCryptographicHash>
#include <QModelIndexList>
#include <QItemSelectionModel>

CollaborationWidget::CollaborationWidget(QWidget *parent)
    : QWidget(parent)
{
    setupUI();
    loadUserData();
}

void CollaborationWidget::setupUI()
{
    // 创建主布局
    QVBoxLayout *mainLayout = new QVBoxLayout(this);
    mainLayout->setContentsMargins(20, 20, 20, 20);
    mainLayout->setSpacing(15);

    // 标题
    QLabel *titleLabel = new QLabel("协作管理", this);
    titleLabel->setStyleSheet("font-size: 24px; font-weight: bold; color: #2c6e49;");
    mainLayout->addWidget(titleLabel);

    // 用户表格
    userTable = new QTableView(this);
    userTable->setStyleSheet("QTableView {"
                            "  border: 1px solid #c8e6c9;"
                            "  border-radius: 4px;"
                            "  outline: none;"
                            "}"
                            "QHeaderView::section {"
                            "  background-color: #e8f5e9;"
                            "  padding: 10px;"
                            "  border: none;"
                            "  font-weight: bold;"
                            "  font-size: 14px;"
                            "}"
                            "QTableView::item {"
                            "  padding: 8px;"
                            "}"
                            "QTableView::item:selected {"
                            "  background-color: #e8f5e9;"
                            "  color: #2c6e49;"
                            "  border: none;"
                            "  outline: none;"
                            "}");

    // 设置滚动条策略
    userTable->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
    userTable->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);

    // 设置选择行为
    userTable->setSelectionBehavior(QAbstractItemView::SelectRows);
    userTable->setSelectionMode(QAbstractItemView::SingleSelection);
    userTable->verticalHeader()->setVisible(false);

    // 禁用编辑功能
    userTable->setEditTriggers(QAbstractItemView::NoEditTriggers);

    // 移除焦点框
    userTable->setFocusPolicy(Qt::NoFocus);

    mainLayout->addWidget(userTable, 1); // 添加拉伸因子1

    // 底部按钮区域
    QHBoxLayout *buttonLayout = new QHBoxLayout();
    buttonLayout->setAlignment(Qt::AlignRight);

    QPushButton *addButton = new QPushButton("添加用户", this);
    editButton = new QPushButton("编辑用户", this); // 保存指针
   QPushButton * deleteButton = new QPushButton("删除用户", this); // 保存指针

    // 设置按钮样式
    QString buttonStyle = "QPushButton {"
                          "  background-color: #4b8a29;"
                          "  color: white;"
                          "  height: 35px;"
                          "  padding: 0 20px;"
                          "  border-radius: 4px;"
                          "}"
                          "QPushButton:hover {"
                          "  background-color: #3e7321;"
                          "}";

    addButton->setStyleSheet(buttonStyle);
    editButton->setStyleSheet(buttonStyle);
    deleteButton->setStyleSheet(buttonStyle);

    // 启用按钮
    addButton->setEnabled(true);
    editButton->setEnabled(true);
    deleteButton->setEnabled(true);

    // 连接按钮信号
    connect(addButton, &QPushButton::clicked, this, &CollaborationWidget::onAddUserClicked);
    connect(editButton, &QPushButton::clicked, this, &CollaborationWidget::onEditUserClicked);
    connect(deleteButton, &QPushButton::clicked, this, &CollaborationWidget::onDeleteUserClicked);

    buttonLayout->addWidget(addButton);
    buttonLayout->addWidget(editButton);
    buttonLayout->addWidget(deleteButton);

    // 将按钮布局添加到主布局
    mainLayout->addLayout(buttonLayout);

    // 设置布局
    setLayout(mainLayout);
}

void CollaborationWidget::loadUserData()
{
    // 创建数据库模型
    userModel = new QSqlTableModel(this);
    userModel->setTable("user");
    userModel->setEditStrategy(QSqlTableModel::OnManualSubmit);

    // 设置列标题
    userModel->setHeaderData(0, Qt::Horizontal, "账号");
    userModel->setHeaderData(1, Qt::Horizontal, "密码");
    userModel->setHeaderData(2, Qt::Horizontal, "权限");

    // 加载数据
    if (!userModel->select()) {
        QMessageBox::critical(this, "数据库错误",
                             "无法加载用户数据:\n" + userModel->lastError().text());
        return;
    }

    // 设置表格模型
    userTable->setModel(userModel);

    // 调整列宽
    userTable->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);

    // 自定义权限显示
    for (int i = 0; i < userModel->rowCount(); ++i) {
        QModelIndex index = userModel->index(i, 2);
        QString permission = userModel->data(index).toString();

        if (permission == "rw") {
            userModel->setData(index, "可读可写");
        } else if (permission == "r") {
            userModel->setData(index, "只读");
        }
    }

    // 设置行高
    userTable->verticalHeader()->setDefaultSectionSize(40);

    // 添加空状态提示
    if (userModel->rowCount() == 0) {
        QLabel *emptyLabel = new QLabel("没有用户数据", userTable);
        emptyLabel->setAlignment(Qt::AlignCenter);
        emptyLabel->setStyleSheet("font-size: 16px; color: #757575;");
        userTable->setIndexWidget(QModelIndex(), emptyLabel);
    }
}

void CollaborationWidget::onAddUserClicked()
{
    // 创建添加用户对话框
    QDialog dialog(this);
    dialog.setWindowTitle("添加新用户");
    dialog.setFixedSize(380, 220);

    // 创建主布局
    QVBoxLayout *mainLayout = new QVBoxLayout(&dialog);
    mainLayout->setSpacing(10);

    // 创建表单布局
    QFormLayout *formLayout = new QFormLayout();
    formLayout->setSpacing(10);
    formLayout->setContentsMargins(10, 10, 10, 10);

    // 账号输入框
    QLineEdit *usernameEdit = new QLineEdit(&dialog);
    usernameEdit->setPlaceholderText("请输入账号");
    formLayout->addRow("账号:", usernameEdit);

    // 密码输入框
    QLineEdit *passwordEdit = new QLineEdit(&dialog);
    passwordEdit->setPlaceholderText("请输入密码");
    passwordEdit->setEchoMode(QLineEdit::Password);
    passwordEdit->setFixedHeight(32);
    formLayout->addRow("密码:", passwordEdit);

    // 确认密码输入框
    QLineEdit *confirmPasswordEdit = new QLineEdit(&dialog);
    confirmPasswordEdit->setPlaceholderText("请再次输入密码");
    confirmPasswordEdit->setEchoMode(QLineEdit::Password);
    confirmPasswordEdit->setFixedHeight(32);
    formLayout->addRow("确认密码:", confirmPasswordEdit);

    // 权限选择
    QComboBox *permissionCombo = new QComboBox(&dialog);
    permissionCombo->addItem("只读 (r)", "r");
    permissionCombo->addItem("可读可写 (rw)", "rw");
    permissionCombo->setFixedHeight(32);
    formLayout->addRow("权限:", permissionCombo);

    // 添加表单到主布局
    mainLayout->addLayout(formLayout);

    // 按钮框
    QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel, &dialog);
    buttonBox->setCenterButtons(true);
    connect(buttonBox, &QDialogButtonBox::accepted, &dialog, &QDialog::accept);
    connect(buttonBox, &QDialogButtonBox::rejected, &dialog, &QDialog::reject);

    // 添加按钮框到主布局
    mainLayout->addWidget(buttonBox);

    // 设置样式
    dialog.setStyleSheet(
        "QDialog {"
        "  background-color: #f5fbf5;"
        "}"
        "QLabel {"
        "  font-weight: bold;"
        "  color: #2c6e49;"
        "}"
        "QLineEdit, QComboBox {"
        "  border: 1px solid #c8e6c9;"
        "  border-radius: 4px;"
        "  padding: 5px;"
        "  background-color: white;"
        "}"
        "QLineEdit:focus, QComboBox:focus {"
        "  border: 1px solid #4b8a29;"
        "}"
        "QPushButton {"
        "  background-color: #4b8a29;"
        "  color: white;"
        "  min-width: 80px;"
        "  padding: 6px 12px;"
        "  border-radius: 4px;"
        "}"
        "QPushButton:hover {"
        "  background-color: #3e7321;"
        "}"
    );

    // 显示对话框
    if (dialog.exec() == QDialog::Accepted) {
        // 验证输入
        if (usernameEdit->text().isEmpty()) {
            QMessageBox::warning(this, "输入错误", "账号不能为空");
            return;
        }

        if (passwordEdit->text().isEmpty()) {
            QMessageBox::warning(this, "输入错误", "密码不能为空");
            return;
        }

        if (passwordEdit->text() != confirmPasswordEdit->text()) {
            QMessageBox::warning(this, "输入错误", "两次输入的密码不一致");
            return;
        }

        QString account = usernameEdit->text();

        // 检查账号是否已存在
        QSqlQuery checkQuery;
        checkQuery.prepare("SELECT COUNT(*) FROM user WHERE admin = ?");
        checkQuery.addBindValue(account);

        if (!checkQuery.exec()) {
            QMessageBox::critical(this, "数据库错误", "检查账号失败: " + checkQuery.lastError().text());
            return;
        }

        if (checkQuery.next() && checkQuery.value(0).toInt() > 0) {
            QMessageBox::warning(this, "账号已存在", "该账号已被使用，请选择其他账号");
            return;
        }

        // 加密密码
        QString password = passwordEdit->text();


        // 插入新用户
        QSqlQuery insertQuery;
        insertQuery.prepare("INSERT INTO user (admin, passwd, permission) VALUES (?, ?, ?)");
        insertQuery.addBindValue(account);
        insertQuery.addBindValue(password);
        insertQuery.addBindValue(permissionCombo->currentData().toString());

        if (insertQuery.exec()) {
            QMessageBox::information(this, "添加成功", "用户添加成功");
            loadUserData(); // 刷新用户列表
        } else {
            QMessageBox::critical(this, "添加失败", "添加用户失败: " + insertQuery.lastError().text());
        }
    }
}

void CollaborationWidget::onEditUserClicked()
{
    // 获取选中的行
    QModelIndexList selectedIndexes = userTable->selectionModel()->selectedRows();
    if (selectedIndexes.isEmpty()) {
        QMessageBox::warning(this, "未选择用户", "请先选择一个用户进行编辑");
        return;
    }

    // 获取选中的行号
    int selectedRow = selectedIndexes.first().row();

    // 获取用户数据
    QString account = userModel->data(userModel->index(selectedRow, 0)).toString();
    QString permission = userModel->data(userModel->index(selectedRow, 2)).toString();

    // 创建编辑用户对话框
    QDialog dialog(this);
    dialog.setWindowTitle("编辑用户");
    dialog.setFixedSize(380, 220);

    // 创建主布局
    QVBoxLayout *mainLayout = new QVBoxLayout(&dialog);
    mainLayout->setSpacing(10);

    // 创建表单布局
    QFormLayout *formLayout = new QFormLayout();
    formLayout->setSpacing(10);
    formLayout->setContentsMargins(10, 10, 10, 10);

    // 账号显示（不可编辑）
    QLineEdit *usernameEdit = new QLineEdit(&dialog);
    usernameEdit->setText(account);
    usernameEdit->setEnabled(false);
    formLayout->addRow("账号:", usernameEdit);

    // 密码输入框
    QLineEdit *passwordEdit = new QLineEdit(&dialog);
    passwordEdit->setPlaceholderText("请输入新密码 (留空则不修改)");
    passwordEdit->setEchoMode(QLineEdit::Password);
    passwordEdit->setFixedHeight(32);
    formLayout->addRow("密码:", passwordEdit);

    // 确认密码输入框
    QLineEdit *confirmPasswordEdit = new QLineEdit(&dialog);
    confirmPasswordEdit->setPlaceholderText("请再次输入新密码");
    confirmPasswordEdit->setEchoMode(QLineEdit::Password);
    confirmPasswordEdit->setFixedHeight(32);
    formLayout->addRow("确认密码:", confirmPasswordEdit);

    // 权限选择
    QComboBox *permissionCombo = new QComboBox(&dialog);
    permissionCombo->addItem("只读 (r)", "r");
    permissionCombo->addItem("可读可写 (rw)", "rw");
    permissionCombo->setCurrentIndex(permission == "rw" ? 1 : 0);
    permissionCombo->setFixedHeight(32);
    formLayout->addRow("权限:", permissionCombo);

    // 添加表单到主布局
    mainLayout->addLayout(formLayout);

    // 按钮框
    QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel, &dialog);
    buttonBox->setCenterButtons(true);
    connect(buttonBox, &QDialogButtonBox::accepted, &dialog, &QDialog::accept);
    connect(buttonBox, &QDialogButtonBox::rejected, &dialog, &QDialog::reject);

    // 添加按钮框到主布局
    mainLayout->addWidget(buttonBox);

    // 设置样式
    dialog.setStyleSheet(
        "QDialog {"
        "  background-color: #f5fbf5;"
        "}"
        "QLabel {"
        "  font-weight: bold;"
        "  color: #2c6e49;"
        "}"
        "QLineEdit, QComboBox {"
        "  border: 1px solid #c8e6c9;"
        "  border-radius: 4px;"
        "  padding: 5px;"
        "  background-color: white;"
        "}"
        "QLineEdit:focus, QComboBox:focus {"
        "  border: 1px solid #4b8a29;"
        "}"
        "QPushButton {"
        "  background-color: #4b8a29;"
        "  color: white;"
        "  min-width: 80px;"
        "  padding: 6px 12px;"
        "  border-radius: 4px;"
        "}"
        "QPushButton:hover {"
        "  background-color: #3e7321;"
        "}"
    );

    // 显示对话框
    if (dialog.exec() == QDialog::Accepted) {
        // 获取新密码
        QString newPassword = passwordEdit->text();
        QString confirmPassword = confirmPasswordEdit->text();

        // 验证密码一致性
        if (!newPassword.isEmpty() && newPassword != confirmPassword) {
            QMessageBox::warning(this, "输入错误", "两次输入的密码不一致");
            return;
        }

        // 获取新权限
        QString newPermission = permissionCombo->currentData().toString();

        // 更新用户信息
        QSqlQuery updateQuery;

        if (!newPassword.isEmpty()) {
            // 更新密码和权限

            updateQuery.prepare("UPDATE user SET passwd = ?, permission = ? WHERE admin = ?");
            updateQuery.addBindValue(newPassword);
            updateQuery.addBindValue(newPermission);
            updateQuery.addBindValue(account);
        } else {
            // 只更新权限
            updateQuery.prepare("UPDATE user SET permission = ? WHERE admin = ?");
            updateQuery.addBindValue(newPermission);
            updateQuery.addBindValue(account);
        }

        if (updateQuery.exec()) {
            if (updateQuery.numRowsAffected() > 0) {
                QMessageBox::information(this, "更新成功", "用户信息已更新");
                refreshUserList(); // 刷新用户列表
            } else {
                QMessageBox::warning(this, "更新失败", "未更新任何记录");
            }
        } else {
            QMessageBox::critical(this, "更新失败", "更新用户失败: " + updateQuery.lastError().text());
        }
    }
}

void CollaborationWidget::onDeleteUserClicked()
{
    // 获取选中的行
    QModelIndexList selectedIndexes = userTable->selectionModel()->selectedRows();
    if (selectedIndexes.isEmpty()) {
        QMessageBox::warning(this, "未选择用户", "请先选择一个用户进行删除");
        return;
    }

    // 获取选中的行号
    int selectedRow = selectedIndexes.first().row();

    // 获取用户账号
    QString account = userModel->data(userModel->index(selectedRow, 0)).toString();

    // 检查是否是管理员账号
    if (account == "1") {
        QMessageBox::warning(this, "禁止删除", "管理员账号不能被删除");
        return;
    }

    // 确认删除对话框
    QMessageBox::StandardButton reply;
    reply = QMessageBox::question(this, "确认删除",
                                QString("确定要删除用户 '%1' 吗？").arg(account),
                                QMessageBox::Yes | QMessageBox::No);

    if (reply == QMessageBox::Yes) {
        // 执行删除操作
        QSqlQuery deleteQuery;
        deleteQuery.prepare("DELETE FROM user WHERE admin = ?");
        deleteQuery.addBindValue(account);

        if (deleteQuery.exec()) {
            if (deleteQuery.numRowsAffected() > 0) {
                QMessageBox::information(this, "删除成功", "用户已成功删除");
                refreshUserList(); // 刷新用户列表
            } else {
                QMessageBox::warning(this, "删除失败", "未删除任何记录");
            }
        } else {
            QMessageBox::critical(this, "删除失败", "删除用户失败: " + deleteQuery.lastError().text());
        }
    }
}

void CollaborationWidget::refreshUserList()
{
    // 重新加载数据
    if (userModel) {
        userModel->select();

        // 重新应用权限显示转换
        for (int i = 0; i < userModel->rowCount(); ++i) {
            QModelIndex index = userModel->index(i, 2);
            QString permission = userModel->data(index).toString();

            if (permission == "rw") {
                userModel->setData(index, "可读可写");
            } else if (permission == "r") {
                userModel->setData(index, "只读");
            }
        }

        // 更新空状态提示
        if (userModel->rowCount() == 0) {
            QLabel *emptyLabel = new QLabel("没有用户数据", userTable);
            emptyLabel->setAlignment(Qt::AlignCenter);
            emptyLabel->setStyleSheet("font-size: 16px; color: #757575;");
            userTable->setIndexWidget(QModelIndex(), emptyLabel);
        } else {
            // 移除空状态提示
            userTable->setIndexWidget(QModelIndex(), nullptr);
        }
    }
}
